import React, { useEffect, useState } from 'react';
import { Table, Empty, Button, Input, Icon, message, Modal } from 'antd';
import { getUsers } from '@api/user';
import copyToClipboard from '@util/copy-to-clipboard';
import _ from 'lodash';
import AddUserManage from './components/add-user-manage';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Operator from '../../user-manage/operator/index';
import { getStaffinfo } from './../../../api/system';
import moment from 'moment';
import './index.less';

const Search = Input.Search;
const prefixCls = 'user-manage';
const PortManageTable = props => {
  const [addManageModal, setAddManageModal] = useState(false);
  const [search, setSearch] = useState();
  const [page, setpage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [tableData, setTableData] = useState([]);
  const [isLoadingUsers, setIsLoadingUsers] = useState(false);
  const [total, setTotal] = useState(0);
  const [password, setPassword] = useState('');
  const [statusModalVisble, setStatusModalVisble] = useState(false);
  const [addEditModalType, setAddEditModalType] = useState();
  const [detail, setDetail] = useState({});
  const [filter, setFilter] = useState({});
  const [key, setKey] = useState();
  const [Rkey, setRkey] = useState();
  const [disabledkey, setDisabledkey] = useState({});
  const [isAddSucceed, setIsAddSucceed] = useState(true);
  const { history, roles } = props;

  // 用户角色
  const filteredRoles = roles
    .filter(i => i && !i.is_admin)
    .map(r => {
      return { text: r.name, value: r._id };
    });

  const loadUsers = (page, pageSize) => {
    setIsLoadingUsers(true);
    let query = {
      roleID: filter.role_oid,
      openSiteRange: filter.openSiteRange,
      enableType: filter.enableType
    };
    if (!query.roleID) {
      delete query.roleID;
    }
    if (!query.openSiteRange) {
      delete query.openSiteRange;
    }
    if (!query.enableType) {
      delete query.enableType;
    }
    getUsers({ page, pageSize, search, ...query })
      .then(res => {
        let tableData = _.get(res, 'data.data.list', []);
        //eslint-disable-next-line
        tableData.forEach(user => (user.role_id = _.get(user, 'role_oid._id', '')));
        const count = _.get(res, 'data.data.count', []);
        setTableData(tableData);
        setTotal(count);
      })
      .finally(() => {
        setIsLoadingUsers(false);
      });
  };

  // 打开修改弹窗
  const onEditUser = user => {
    setDetail({
      ...user,
      userInfo: {
        expired: user.expired,
        // eslint-disable-next-line
        role_oid: user.role_oid,
        username: user.username,
        _id: user._id,
        enable: user.enable
      },
      userOid: user._id,
      ...user.staffOid
    });
    setAddManageModal(true);
    setRkey(user.role_oid.name);
    setAddEditModalType('edit');
  };

  const columns = [
    {
      title: '用户名',
      className: 'user-name',
      dataIndex: 'username',
      width: '10%'
    },
    {
      title: '姓名',
      className: 'user-real-name',
      dataIndex: 'staffOid.nickname',
      width: '10%',
      render: (key, rows) => {
        if (key) {
          return key;
        }
        // 初始账户默认展示角色类型名称、
        if (rows.nickname) {
          return rows.nickname;
        }
        return '-';
      }
    },
    {
      title: '用户角色',
      dataIndex: 'role_oid',
      className: 'filters',
      width: '10%',
      render: key => {
        if (!_.get(key, 'name', '')) {
          // eslint-disable-next-line no-param-reassign
          key = { name: '' };
        }
        return key.name;
      },
      filters: filteredRoles,
      filterMultiple: false,
      filteredValue: filter.role_oid && filter.role_oid.length !== 0 ? filter.role_oid : []
    },
    {
      title: '邮箱',
      className: 'user-email',
      dataIndex: 'staffOid.email',
      width: '10%',
      render: (key, row) => {
        if (key) {
          return key;
        } else if (row.email) {
          return row.email;
        } else {
          return '-';
        }
      }
    },
    {
      title: '创建日期',
      className: 'created-time',
      dataIndex: 'created',
      width: '10%'
    },
    {
      title: '失效日期',
      className: 'expired-time',
      dataIndex: 'expired',
      width: '10%',
      render: key => {
        if (key) {
          return moment(key).format('YYYY-MM-DD  HH:mm:ss');
        } else {
          return '-';
        }
      }
    },
    {
      title: '资产管理范围',
      dataIndex: 'openSiteRange',
      className: 'asset-scope',
      render: (key, row) => {
        // 系统管理员和审计员没有资产管理范围
        if (row.isDefaultRole && row.nickname !== '安全管理员') {
          return '-';
        }
        let siteRanges = _.get(row, 'siteRanges', []);
        let text = !key ? '不限制任何资产' : siteRanges.map(r => <p key={r}>{r}</p>);
        return text;
      },
      filters: [{ text: '不限制任何资产', value: false }, { text: '自定义资产范围', value: true }],
      filterMultiple: false,
      filteredValue:
        filter.openSiteRange && filter.openSiteRange.length !== 0 ? filter.openSiteRange : []
    },
    {
      title: '用户状态',
      dataIndex: 'enableType',
      className: 'filters',
      render: key => {
        let param = [
          { text: '已启动', value: 1, icon: <Icon type="check-circle" />, color: 'green' },
          { text: '已禁用', value: 2, icon: <Icon type="close-circle" />, color: 'red' },
          { text: '已失效', value: 3, icon: <Icon type="minus-circle" />, color: '' }
        ];
        let item = param.find(r => r.value === key);
        return item ? (
          <>
            <span style={{ fontSize: 20, color: item.color, marginRight: 10 }}>{item.icon}</span>
            {item.text}
          </>
        ) : null;
      },
      filters: [
        { text: '已启动', value: 1 },
        { text: '已禁用', value: 2 },
        { text: '已失效', value: 3 }
      ],
      filterMultiple: false,
      filteredValue: filter.enableType && filter.enableType.length !== 0 ? filter.enableType : []
    },
    {
      title: '操作',

      width: '15%',
      render: row => {
        const operator = (
          <Operator
            row={row}
            onEditUser={() => onEditUser(row)}
            afterReset={password => {
              setIsAddSucceed(false);
              setPassword(password);
              setStatusModalVisble(true);
            }}
            afterDelete={() => loadUsers(page, pageSize)}
          />
        );
        return operator;
      }
    }
  ];

  // 新增成功callback
  const onSuccess = (p, add) => {
    setAddManageModal(false);
    if (add) {
      message.success('新增成功');
      setStatusModalVisble(true);
    }
    setDisabledkey();
    setRkey();
    setPassword(p);
    loadUsers(page, pageSize);
  };

  const onTableChange = (page, filter) => {
    setpage(page.current);
    setPageSize(page.pageSize);
    setFilter(filter);
  };

  const onAddUser = () => {
    setAddEditModalType('');
    setKey();
    setDetail({});
    setAddManageModal(true);
  };

  // 清空弹框内容
  const clearAddUserManage = () => {
    setAddManageModal(false), setDetail({}), setDisabledkey(), setRkey();
  };

  useEffect(() => {
    loadUsers(page, pageSize);
    const params = new URLSearchParams(history.location.search);
    setKey(params.get('id'));
  }, []);

  useEffect(() => {
    if (key) {
      getStaffinfo(`staffId=${key}`)
        .then(res => {
          let role = _.get(res, 'data.data.userInfo.role_oid.name', null);
          if (!role) {
            setDisabledkey({ staffOid: true });
            setRkey('未开通');
          }
          if (role === '安全操作员' || role === '安全管理员' || role === '操作员') {
            setDisabledkey({ staffOid: true, username: true });
            setRkey(role);
          }
          setDetail(_.get(res, 'data.data', {}));
        })
        .catch();
      setAddEditModalType();
      setAddManageModal(true);
    }
  }, key);

  useEffect(() => {
    loadUsers(page, pageSize);
  }, [page, pageSize, search, filter]);

  const onCopyPassword = () => {
    const res = copyToClipboard(password);
    if (res) {
      message.success('成功');
    } else {
      message.error('失败');
    }
    setStatusModalVisble(false);
  };

  const pagination = {
    current: page,
    pageSize: pageSize,
    total: total,
    showQuickJumper: true,
    showSizeChanger: true,
    showTotal: num => `共 ${num} 条`,
    size: 'small'
  };
  const onCloseStatueModal = () => {
    setStatusModalVisble(false);
    // 解决编辑与新增文字的闪烁问题
    setTimeout(() => {
      setIsAddSucceed(true);
    }, 300);
  };
  const addEditStatusModalFooter = [
    <Button className="close" key="0" onClick={onCloseStatueModal}>
      关闭
    </Button>,
    <Button className="copy" key="1" type="primary" onClick={onCopyPassword}>
      复制密码
    </Button>
  ];
  return (
    <>
      <div className={`${prefixCls}`}>
        <div className={`${prefixCls}-header`}>
          <div className={`${prefixCls}-header-left`}>
            <Button type="primary" onClick={() => onAddUser()}>
              添加用户
            </Button>
          </div>
          <div className={`${prefixCls}-header-right`}>
            <Search
              enterButton
              placeholder="请输入用户名/姓名"
              onSearch={search => {
                setpage(1), setSearch(search);
              }}
            />
          </div>
        </div>
        <div className={`${prefixCls}-body`}>
          <Table
            columns={columns}
            pagination={pagination}
            dataSource={tableData}
            scroll={{ y: 445 }}
            onChange={onTableChange}
            loading={{ spinning: isLoadingUsers, tip: '加载中' }}
            locale={{
              emptyText: <Empty description={'暂无数据'} image={Empty.PRESENTED_IMAGE_SIMPLE} />
            }}
          />
        </div>
      </div>
      <AddUserManage
        edit={addEditModalType}
        visible={addManageModal}
        onCancel={clearAddUserManage}
        detail={detail}
        password={password}
        onSuccess={onSuccess}
        disabledkey={disabledkey}
        Rkey={Rkey}
      />
      <Modal
        maskClosable={false}
        className={'user-center-add-edit-status-modal'}
        visible={statusModalVisble}
        title={null}
        footer={addEditStatusModalFooter}
        onCancel={onCloseStatueModal}
      >
        <div className="content">
          <Icon className="icon" type={'check-circle'} theme="twoTone" />
          <p className="info">{isAddSucceed ? '添加用户成功' : '重置用户密码成功'}</p>
          <p className="password">
            {isAddSucceed ? `用户初始密码: ${password}` : `用户重置密码${password}`}
          </p>
        </div>
      </Modal>
    </>
  );
};

PortManageTable.propTypes = {
  history: PropTypes.object,
  roles: PropTypes.array
};
const mapStateToProps = state => {
  return {
    roles: _.get(state, 'role.roles', [])
  };
};

export default connect(mapStateToProps)(PortManageTable);
